import { angle1, angle2, mo1, mo2, temp_str, start_collection_mo1, start_collection_mo2, start_collection_state, motionmodeListgroupItemState, train_working, cancelmotioning, train_end, tor1, tor2 } from '$lib/data';

import { fromStore } from 'svelte/store';

import { Window } from '@tauri-apps/api/window'

// //临时串口字符
// let now_str: string = "";
// let mo1_temp: number[] = [];
// let mo2_temp: number[] = [];

// let before_str_split: string | undefined = undefined;

// export async function recv_serial_event_str(value: string) {
//     now_str = value;
//     if (before_str_split == undefined) {

//     } else {
//         now_str = before_str_split + now_str;
//         before_str_split = undefined;
//         fromStore(temp_str).current = now_str;
//     };
//     recv_serial_event_str_split(now_str);
// };

// //字符分割是为了防止最后一个没传完，也可以使用rs232的流控，但是因为测试时不是正常的DB9接口，选择了不流控。
// function recv_serial_event_str_split(str: string) {
//     let str_split = str.split(";");
//     let length = str_split.length;
//     let num = 0;
//     // console.log(length);
//     while(num < length - 1){
//         recv_serial_event_str_split_avg(str_split[num].split(" "));
//         num++;
//     }

//     before_str_split = str_split.pop();

//     // console.log("the pop:" + before_str_split);
// };

// // 串口使用的是Windows api，扫描周期是1ms左右，单片机上发速度远超上位机（us级上发）。
// // 所以对这段时间的上报的值，求平均，作为目前值。
// function recv_serial_event_str_split_avg(str: string[]) {
//     let length = str.length;
//     let num = 0;
//     while(num < length){
//         switch (num) {
//             case 0:
//                 mo1_temp.push(Number(str[num]));
//                 break;
//             case 1:
//                 mo2_temp.push(Number(str[num]));
//                 break;
//         }
//         num++;
//     }
//     update_mo();
// };

export function update_mo(str: string) {
    // let mo1_value = mo1_temp.reduce((a, b) => a + b, 0) / mo1_temp.length;
    // let mo2_value = mo2_temp.reduce((a, b) => a + b, 0) / mo2_temp.length;

    // mo1_temp = [];
    // mo2_temp = [];

    // fromStore(mo1).current.push(Number(mo1_value));
    // fromStore(mo2).current.push(Number(mo2_value));
    
    // fromStore(angle1).current = Number(mo1_value) / 45 * 0.1745;
    // fromStore(angle2).current = Number(mo2_value) / 45 * 0.1745;

    const [mo1_value, mo2_value, mo1_angle, mo2_angle, mo1_angle_rad, mo2_angle_rad, mo1_torque, mo2_torque] = str.split(" ");
    fromStore(temp_str).current = `${mo1_angle} ${mo2_angle} ${mo1_angle_rad} ${mo2_angle_rad} ${mo1_torque} ${mo2_torque}`;

    //为了防止卡顿，暂时限制历史图表
    if(fromStore(mo1).current.length > 1000){
        fromStore(mo1).current = fromStore(mo1).current.splice(100,1000);
    }
    if(fromStore(mo2).current.length > 1000){
        fromStore(mo2).current = fromStore(mo2).current.splice(100,1000);
    }
    if(fromStore(tor1).current.length > 1000){
        fromStore(tor1).current = fromStore(tor1).current.splice(100,1000);
    }
    if(fromStore(tor2).current.length > 1000){
        fromStore(tor2).current = fromStore(tor2).current.splice(100,1000);
    }

    fromStore(mo1).current.push(Number(mo1_angle));
    fromStore(mo2).current.push(Number(-mo2_angle));//下面发来是反的
    fromStore(angle2).current = Number(mo1_angle_rad);//canvas动画上臂前臂是反的
    fromStore(angle1).current = Number(-mo2_angle_rad);//下面发来是反的
    fromStore(tor1).current.push(Number(mo1_torque));
    fromStore(tor2).current.push(Number(mo2_torque));

    if (fromStore(start_collection_state).current) {
        fromStore(start_collection_mo1).current = fromStore(start_collection_mo1).current.concat(JSON.parse(mo1_value));
        fromStore(start_collection_mo2).current = fromStore(start_collection_mo2).current.concat(JSON.parse(mo2_value));
    }
    console.log(fromStore(start_collection_mo1).current+"+"+fromStore(start_collection_mo2).current);

}

export async function closeWindow() {
    try {
        // 获取当前窗口
        const window = await Window.getCurrent();
        // 关闭窗口
        await window.close();
    } catch (error) {
        console.error('Failed to close window:', error);
    }
}

export async function cancelmotion() {
    fromStore(motionmodeListgroupItemState).current = [false, false, false, false];

    fromStore(cancelmotioning).current = false;
    setTimeout(() => {fromStore(train_end).current = false;}, 2000);

}
